package com.skivingcloud.report.utils;

import com.skivingcloud.common.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class VelocityUtil {
	private static final Logger log = LoggerFactory.getLogger(VelocityUtil.class);
	/**
     * 替换的模板中的参数
     *
     * @param template 模板
     * @param parameters 参数
     * @return 替换后的文本
     */
    public static String parse(final String template, final Map<String, Object> parameters) {
        return parse(template, parameters, "report");
    }
    
    /**
     * 替换的模板中的参数
     *
     * @param template 模板
     * @param parameters 参数
     * @param logTag ？
     * @return 替换后的文本
     */
    public static String parse(final String template, final Map<String, Object> parameters, final String logTag) {
    	if (parameters == null) {
			return template;
		}
    	try (StringWriter writer = new StringWriter()) {
            Velocity.init();
            final VelocityContext context = new VelocityContext();
			parameters.forEach((key, value) -> {
				if(value instanceof List){
					context.put(key, ((List<?>) value).stream().map(l -> {
						return "'" + l + "'";
					}).collect(Collectors.joining(",")));
				}else{
					context.put(key, StringUtils.isBlank(value.toString()) ? "''" : "'" + value + "'");
				}
			});
            Velocity.evaluate(context, writer, logTag, template);
            return writer.toString();
        } catch (final Exception ex) {
			log.error(ex.getMessage(), ex);
            throw new BusinessException("模板引擎解析出错，错误信息："+ex.getMessage());
        }
    }
    
    public static String parseInfluxdb(final String template, final Map<String, Object> parameters, final String logTag) {
    	if (parameters == null) {
			return template;
		}
    	try (StringWriter writer = new StringWriter()) {
            Velocity.init();
            final VelocityContext context = new VelocityContext();
			parameters.forEach((key, value) -> {
				if(value instanceof List){
					context.put(key, ((List<?>) value).stream().map(l -> {
						return (String)l;
					}).collect(Collectors.joining("|")));
				}else{
					context.put(key, StringUtils.isBlank(value.toString()) ? "" : value);
				}
			});
            Velocity.evaluate(context, writer, logTag, template);
            return writer.toString();
        } catch (final Exception ex) {
			log.error(ex.getMessage(), ex);
			throw new BusinessException("模板引擎解析出错，错误信息："+ex.getMessage());
        }
    }
    
    public static String simpleParse(final String template, final Map<String, Object> parameters) {
    	try (StringWriter writer = new StringWriter()) {
    		  Velocity.init();
              final VelocityContext context = new VelocityContext();
              for (final Entry<String, Object> kvset : parameters.entrySet()) {
            	  if(kvset.getValue() != null)
            	  {
            		  context.put(kvset.getKey(),  kvset.getValue());
            	  }else {
            		  context.put(kvset.getKey(), "");
            	  }
              }
              Velocity.evaluate(context, writer, "report", template);
              return writer.toString();
    	}catch (final Exception ex) {
			log.error(ex.getMessage(), ex);
			throw new BusinessException("模板引擎解析出错，错误信息："+ex.getMessage());
        }
    }
}
